﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

namespace Fleck.Samples.ConsoleApp
{
    /// <summary>
    /// 示例服务器
    /// </summary>
    class Server
    {
        static WebSocketServer server;
        public void Start()
        {
            FleckLog.Level = LogLevel.Info;
            var allSockets = new List<WebSocketConnection>();
            server = new WebSocketServer("ws://0.0.0.0:8181");
            server.Start(socket =>
                {
                    socket.OnOpen = () =>
                        {
                            var conn = (WebSocketConnection)socket;
                            Console.WriteLine(string.Format("Open! {0}:{1};", conn.Socket.RemoteIpAddress, conn.Socket.RemotePort.ToString("D5")));
                            allSockets.Add(conn);
                        };
                    socket.OnClose = () =>
                        {
                            var conn = (WebSocketConnection)socket;
                            Console.WriteLine(string.Format("Close! {0}:{1};", conn.Socket.RemoteIpAddress, conn.Socket.RemotePort.ToString("D5")));
                            allSockets.Remove(conn);
                        };
                    socket.OnMessage = (message,conn) =>
                        {

                            Console.WriteLine(message);
                            Send(conn, message);
                            allSockets.ToList().ForEach(s =>
                            {
                                // Send(s, message);
                            });
                        };
                    socket.OnBinary = bytes =>
                        {
                            string message = BitConverter.ToString(bytes);
                            Console.WriteLine(message);
                            allSockets.ToList().ForEach(s =>
                            {
                                Send(s, message);
                            });
                        };
                });


            var input = Console.ReadLine();
            while (input != "exit")
            {
                foreach (var socket in allSockets.ToList())
                {
                    socket.Send(input);
                }
                input = Console.ReadLine();
            }

        }


        public static void Send(IWebSocketConnection s, string message)
        {
            WebSocketConnection conn = s as WebSocketConnection;

            s.Send(string.Format("{0}:{1};Echo:  {2},{3}", conn.Socket.RemoteIpAddress, conn.Socket.RemotePort.ToString("D5"), message, DateTime.Now));
        }
    }
}
